import {defineStore} from 'pinia';
import {ref} from 'vue'
import {getPermissionKeys, getPermissionList,deletePermissionById} from "@/api/modules/permission";
import useMessage from "@/plugin/useMessage";

export const usePermissionStore = defineStore('permission', () => {
  const permissionKeyList = ref<string[]>([])
  const permissions = ref<PermissionRow[]>([])
  const getPermissions = async () => {
    let res  = await getPermissionList()
    if(res.code === 200){
      permissions.value = res.data
    }
  }
  const getPermissionKeyList = async () => {
    let res  = await getPermissionKeys()
    if(res.code === 200){
      permissionKeyList.value = res.data
    }
  }
  const deletePermission = async (id:number) => {
    let res = await deletePermissionById(id)
    if(res.code === 200){
      permissions.value = permissions.value.filter(item => item.id !== id)
    }
    useMessage(res.code,res.message)
  }
  const hasPermission = (key:string) => {
    let isHas = permissionKeyList.value.includes(key)
    if (!isHas){
      useMessage(403,'您没有权限');
      return false
    }
    return true
  }

  return {
    permissions,
    hasPermission,
    getPermissions,
    getPermissionKeyList,
    deletePermission
  }
})